import React from 'react';
import { Card, Form, Input, Select, DatePicker, Button, Space, Table, Popover, Tag } from 'antd';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

// 模拟字典数据（原 Vue 版本通过 $api.dict 获取）
const payStateList = [
  { value: '0', label: '未付款' },
  { value: '1', label: '已付款' },
  { value: '2', label: '已退款' },
];

const payTypeList = [
  { value: '1', label: '微信' },
  { value: '2', label: '支付宝' },
  { value: '3', label: '现金' },
  { value: '5', label: '会员卡' },
];

function getDictLabel(list, value) {
  const item = list.find((i) => String(i.value) === String(value));
  return item ? item.label : value;
}

// 模拟订单数据
const mockOrders = [
  {
    id: 1,
    userName: '张三',
    equipmentNo: 'EQ-10001',
    equipmentName: '咖啡机-北京一店',
    goodsName: '美式咖啡',
    ordersGoods: [
      { goodsName: '美式咖啡', aisleNo: 'A01', costPrice: 8.5, sellingPrice: 12.0, vatRate: 10, buyNum: 1 },
      { goodsName: '加糖包', aisleNo: 'B03', costPrice: 0.5, sellingPrice: 1.0, vatRate: 10, buyNum: 1 },
    ],
    buyTime: '2025-10-10 09:12:33',
    payState: '1',
    aisleNo: 'A01',
    costPrice: 9.0,
    sellingPrice: 13.0,
    vatRate: 10,
    payPrice: 13.0,
    discountPrice: 0.0,
    payablePrice: 13.0,
    buyNum: 2,
    payType: '1',
    icard: '',
    orderNumber: 'ORD202510100001',
    trxNo: 'TRX-987654',
    createTime: '2025-10-10 09:12:33',
  },
  {
    id: 2,
    userName: '李四',
    equipmentNo: 'EQ-20002',
    equipmentName: '零食机-上海二店',
    goodsName: '薯片',
    ordersGoods: null,
    buyTime: '2025-10-09 18:22:10',
    payState: '2',
    aisleNo: 'C05',
    costPrice: 6.0,
    sellingPrice: 9.0,
    vatRate: 8,
    payPrice: 9.0,
    discountPrice: 1.0,
    payablePrice: 8.0,
    buyNum: 1,
    payType: '5',
    icard: '8888-1234-5678',
    orderNumber: 'ORD202510090002',
    trxNo: 'TRX-654321',
    createTime: '2025-10-09 18:22:10',
  },
];

export default function OrderList() {
  const [form] = Form.useForm();
  const [loading, setLoading] = React.useState(false);
  const [page, setPage] = React.useState({ pageSize: 10, pageIndex: 1, totalSize: mockOrders.length });
  const [search, setSearch] = React.useState({
    goodsName: '',
    equipmentNo: '',
    equipmentName: '',
    orderNumber: '',
    trxNo: '',
    payState: '',
    payType: '',
    startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    userName: '',
    sort: undefined,
    order: undefined,
  });
  const [dateRange, setDateRange] = React.useState([
    dayjs().subtract(7, 'day'),
    dayjs(),
  ]);
  const [allOrders] = React.useState(mockOrders);
  const [orderList, setOrderList] = React.useState([]);

  React.useEffect(() => {
    // 初始化搜索与数据
    form.setFieldsValue({
      goodsName: '',
      equipmentNo: '',
      equipmentName: '',
      orderNumber: '',
      trxNo: '',
      payState: '',
      payType: '',
      userName: '',
      dateRange: dateRange,
    });
    applySearch(1);
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function applySearch(newPageIndex = page.pageIndex, newPageSize = page.pageSize, nextSearch = search) {
    setLoading(true);
    // 过滤条件
    const filtered = allOrders.filter((o) => {
      const inDate = (!nextSearch.startTime || !nextSearch.endTime)
        ? true
        : (dayjs(o.createTime).isAfter(dayjs(nextSearch.startTime)) && dayjs(o.createTime).isBefore(dayjs(nextSearch.endTime)));
      const match = (
        (!nextSearch.goodsName || String(o.goodsName).includes(nextSearch.goodsName)) &&
        (!nextSearch.equipmentNo || String(o.equipmentNo).includes(nextSearch.equipmentNo)) &&
        (!nextSearch.equipmentName || String(o.equipmentName).includes(nextSearch.equipmentName)) &&
        (!nextSearch.orderNumber || String(o.orderNumber).includes(nextSearch.orderNumber)) &&
        (!nextSearch.trxNo || String(o.trxNo).includes(nextSearch.trxNo)) &&
        (!nextSearch.userName || String(o.userName).includes(nextSearch.userName)) &&
        (!nextSearch.payState || String(o.payState) === String(nextSearch.payState)) &&
        (!nextSearch.payType || String(o.payType) === String(nextSearch.payType))
      );
      return inDate && match;
    });

    // 排序
    let sorted = filtered.slice();
    if (nextSearch.sort && nextSearch.order) {
      const factor = nextSearch.order === 'ascend' || nextSearch.order === 'asc' ? 1 : -1;
      sorted.sort((a, b) => {
        const av = a[nextSearch.sort];
        const bv = b[nextSearch.sort];
        if (av === bv) return 0;
        return av > bv ? factor : -factor;
      });
    }

    // 分页
    const start = (newPageIndex - 1) * newPageSize;
    const end = start + newPageSize;
    setOrderList(sorted.slice(start, end));
    setPage({ pageIndex: newPageIndex, pageSize: newPageSize, totalSize: sorted.length });
    setLoading(false);
  }

  function onSubmit(values) {
    const next = {
      ...search,
      ...values,
      startTime: values.dateRange && values.dateRange[0] ? values.dateRange[0].format('YYYY-MM-DD HH:mm:ss') : undefined,
      endTime: values.dateRange && values.dateRange[1] ? values.dateRange[1].format('YYYY-MM-DD HH:mm:ss') : undefined,
    };
    setSearch(next);
    setDateRange(values.dateRange || []);
    applySearch(1, page.pageSize, next);
  }

  function resetSearch() {
    const next = {
      goodsName: '',
      equipmentNo: '',
      equipmentName: '',
      orderNumber: '',
      trxNo: '',
      payState: '',
      payType: '',
      startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
      endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      userName: '',
      sort: undefined,
      order: undefined,
    };
    form.setFieldsValue({
      goodsName: '',
      equipmentNo: '',
      equipmentName: '',
      orderNumber: '',
      trxNo: '',
      payState: '',
      payType: '',
      userName: '',
      dateRange: [dayjs().subtract(7, 'day'), dayjs()],
    });
    setSearch(next);
    setDateRange([dayjs().subtract(7, 'day'), dayjs()]);
    applySearch(1, page.pageSize, next);
  }

  function onTableChange(pagination, filters, sorter) {
    const next = {
      ...search,
      sort: sorter && sorter.field,
      order: sorter && sorter.order,
    };
    setSearch(next);
    const newPageIndex = pagination.current || 1;
    const newPageSize = pagination.pageSize || page.pageSize;
    applySearch(newPageIndex, newPageSize, next);
  }

  const goodsPopoverContent = (row) => (
    <div>
      <div style={{ lineHeight: 2, color: '#777' }}>订单明细</div>
      <table width={500} style={{ borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={{ border: '1px solid #000' }}>商品名称</th>
            <th style={{ border: '1px solid #000' }}>货道号</th>
            <th style={{ border: '1px solid #000' }}>成本价</th>
            <th style={{ border: '1px solid #000' }}>售价</th>
            <th style={{ border: '1px solid #000' }}>税率</th>
            <th style={{ border: '1px solid #000' }}>购买数量</th>
          </tr>
        </thead>
        <tbody>
          {(row.ordersGoods || []).map((item, index) => (
            <tr key={index}>
              <td style={{ border: '1px solid #000', textAlign: 'center' }}>{item.goodsName}</td>
              <td style={{ border: '1px solid #000', textAlign: 'center' }}>{item.aisleNo}</td>
              <td style={{ border: '1px solid #000', textAlign: 'center' }}>{item.costPrice}</td>
              <td style={{ border: '1px solid #000', textAlign: 'center' }}>{item.sellingPrice}</td>
              <td style={{ border: '1px solid #000', textAlign: 'center' }}>{item.vatRate}%</td>
              <td style={{ border: '1px solid #000', textAlign: 'center' }}>{item.buyNum}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );

  const columns = [
    { dataIndex: 'userName', title: '用户名', align: 'center', width: 230, sorter: true },
    { dataIndex: 'equipmentNo', title: '设备编号', align: 'center', width: 140, sorter: true },
    { dataIndex: 'equipmentName', title: '设备名称', align: 'center', width: 180, sorter: true },
    {
      dataIndex: 'goodsName',
      title: '商品名称',
      align: 'center',
      width: 180,
      sorter: true,
      render: (_, row) => {
        if (!row.ordersGoods || row.ordersGoods.length === 0) return row.goodsName;
        return (
          <Popover placement="right" trigger="hover" content={goodsPopoverContent(row)}>
            <span style={{ fontSize: 16, cursor: 'pointer' }}>🛒</span>
          </Popover>
        );
      },
    },
    { dataIndex: 'buyTime', title: '购买时间', align: 'center', width: 160, sorter: true },
    {
      dataIndex: 'payState',
      title: '订单状态',
      align: 'center',
      width: 130,
      render: (_, row) => getDictLabel(payStateList, row.payState),
    },
    {
      dataIndex: 'aisleNo',
      title: '货道号',
      align: 'center',
      width: 110,
      render: (_, row) => {
        if (!row.ordersGoods || row.ordersGoods.length === 0) return row.aisleNo;
        return (
          <Popover placement="right" trigger="hover" content={goodsPopoverContent(row)}>
            <span style={{ fontSize: 16, cursor: 'pointer' }}>🛒</span>
          </Popover>
        );
      },
    },
    {
      dataIndex: 'costPrice',
      title: '成本价',
      align: 'center',
      width: 90,
      render: (_, row) => {
        if (!row.ordersGoods || row.ordersGoods.length === 0) return row.costPrice;
        return (
          <Popover placement="right" trigger="hover" content={goodsPopoverContent(row)}>
            <span style={{ fontSize: 16, cursor: 'pointer' }}>🛒</span>
          </Popover>
        );
      },
    },
    {
      dataIndex: 'sellingPrice',
      title: '售价',
      align: 'center',
      width: 100,
      render: (_, row) => {
        if (!row.ordersGoods || row.ordersGoods.length === 0) return row.sellingPrice;
        return (
          <Popover placement="right" trigger="hover" content={goodsPopoverContent(row)}>
            <span style={{ fontSize: 16, cursor: 'pointer' }}>🛒</span>
          </Popover>
        );
      },
    },
    {
      dataIndex: 'vatRate',
      title: '税率',
      align: 'center',
      width: 100,
      render: (_, row) => {
        if (!row.ordersGoods || row.ordersGoods.length === 0) return `${row.vatRate}%`;
        return (
          <Popover placement="right" trigger="hover" content={goodsPopoverContent(row)}>
            <span style={{ fontSize: 16, cursor: 'pointer' }}>🛒</span>
          </Popover>
        );
      },
    },
    { dataIndex: 'payPrice', title: '应付金额', align: 'center', width: 120 },
    { dataIndex: 'discountPrice', title: '优惠金额', align: 'center', width: 130 },
    { dataIndex: 'payablePrice', title: '实付金额', align: 'center', width: 130 },
    { dataIndex: 'buyNum', title: '购买数量', align: 'center', width: 130 },
    {
      dataIndex: 'payType',
      title: '支付方式',
      align: 'center',
      width: 160,
      render: (_, row) => {
        if (String(row.payType) === '5' && row.icard) {
          return (
            <Popover placement="top" trigger="hover" content={<span style={{ fontSize: 16 }}>CardNo: {row.icard}</span>}>
              <Tag color="blue">{getDictLabel(payTypeList, row.payType)}</Tag>
            </Popover>
          );
        }
        return getDictLabel(payTypeList, row.payType);
      },
    },
    { dataIndex: 'orderNumber', title: '订单号', align: 'center', width: 200 },
    { dataIndex: 'createTime', title: '创建时间', align: 'center', width: 160, sorter: true },
  ];

  return (
    <div className="order">
      {/* 查询区域 */}
      <Card style={{ marginBottom: 12 }}>
        <Form form={form} layout="vertical" onFinish={onSubmit}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(220px, 1fr))', gap: 12 }}>
            <Form.Item name="goodsName" label="商品名称"><Input placeholder="输入商品名称" /></Form.Item>
            <Form.Item name="equipmentNo" label="设备编号"><Input placeholder="输入设备编号" /></Form.Item>
            <Form.Item name="equipmentName" label="设备名称"><Input placeholder="输入设备名称" /></Form.Item>
            <Form.Item name="orderNumber" label="订单号"><Input placeholder="输入订单号" /></Form.Item>
            <Form.Item name="trxNo" label="交易号"><Input placeholder="输入交易号" /></Form.Item>
            <Form.Item name="payState" label="订单状态">
              <Select allowClear options={payStateList.map(i => ({ value: i.value, label: i.label }))} placeholder="选择订单状态" />
            </Form.Item>
            <Form.Item name="payType" label="支付方式">
              <Select allowClear options={payTypeList.map(i => ({ value: i.value, label: i.label }))} placeholder="选择支付方式" />
            </Form.Item>
            <Form.Item name="userName" label="用户名"><Input placeholder="输入用户名" /></Form.Item>
            <Form.Item name="dateRange" label="时间范围">
              <RangePicker showTime style={{ width: '100%' }} />
            </Form.Item>
          </div>
          <Space style={{ marginTop: 8 }}>
            <Button type="primary" htmlType="submit">查询</Button>
            <Button onClick={resetSearch}>重置</Button>
          </Space>
        </Form>
      </Card>

      {/* 列表区域 */}
      <Card className="vue-padding radius">
        <Table
          rowKey="id"
          loading={loading}
          dataSource={orderList}
          columns={columns}
          bordered
          scroll={{ y: 638, x: 1500 }}
          pagination={{
            current: page.pageIndex,
            pageSize: page.pageSize,
            total: page.totalSize,
            showSizeChanger: true,
            showQuickJumper: true,
          }}
          onChange={onTableChange}
          locale={{ emptyText: '暂无数据' }}
          style={{ width: '100%' }}
        />
      </Card>
    </div>
  );
}